package net.topicopedia.other;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.labs.repackaged.org.json.JSONArray;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;

@SuppressWarnings("serial")
public class CreateUserTopicsServlet extends HttpServlet {
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
		      throws IOException {
		    System.out.println("Creating new todo ");
		    
		    String jsonString = req.getParameter("json");
		    
		    JSONObject jsonObject = null;
			try {
				jsonObject = new JSONObject(jsonString);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			resp.addHeader("Access-Control-Allow-Origin", "*");
			resp.setContentType("text/plain");
			
			JSONArray jsonlist = null;
			try {
				jsonlist = jsonObject.getJSONArray("items");
			} catch (JSONException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
			
			if ( jsonlist != null )
			{
				for ( int j=0; j < jsonlist.length(); j++ )
				{
					JSONObject json = null;
					try {
						json = (JSONObject) jsonlist.get(j);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					if ( json != null )
					{
						DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
						
						String uuid = null;
						
						try {
							uuid = (String) json.get("uuid");
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						Key userTopicKey;
						Entity userTopic = null;
						
						Boolean addToCategory = false;
						
						if ( uuid != null )
						{
							Long id = Long.parseLong(uuid);
							if ( id > 0 )
							{
								userTopicKey = KeyFactory.createKey("UserTopic", id );
								try {
									userTopic = datastore.get(userTopicKey);
								} catch (EntityNotFoundException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						} 
						
						Key topicKey = null;
						Key userKey = null;
						Entity user = null;
						
						if ( userTopic == null )
						{
							userTopic = new Entity("UserTopic");
							addToCategory = true;
						}
						
						try {
							userKey = KeyFactory.createKey("User", (Long) Long.parseLong((String) json.get("topic")) );
							userTopic.setProperty("user", userKey );
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						try {
						    topicKey = KeyFactory.createKey("Topic", (Long) Long.parseLong((String) json.get("topic")) );
							userTopic.setProperty("topic", topicKey );
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						userTopic.setProperty("items", new Text( req.getParameter("items")) );
						userTopic.setProperty("references", new Text( req.getParameter("references")) );
						userTopicKey = datastore.put( userTopic );
						
						if ( addToCategory ){
							Key categoryKey = null;
							Entity topic = null;
							try {
								topic = datastore.get(topicKey);
								categoryKey = (Key) topic.getProperty("category");
								
							} catch (EntityNotFoundException e2) {
								// TODO Auto-generated catch block
								e2.printStackTrace();
							}
							
							try {
								user = datastore.get(userKey);
								@SuppressWarnings("unchecked")
								HashMap<Key, Long > userTopicCategories = (HashMap<Key, Long>) user.getProperty( "categories" );
								if ( userTopicCategories == null )
								{
									userTopicCategories = new HashMap<Key, Long >();
								}
								if ( categoryKey != null )
								{
									Long count = userTopicCategories.get(categoryKey);
									if ( count != null )
									{
										count++;
										userTopicCategories.put(categoryKey,count);
										user.setProperty("categories", userTopicCategories);
									}
								}
								
							} catch (EntityNotFoundException e3) {
								// TODO Auto-generated catch block
								e3.printStackTrace();
							}
						}
						
						resp.getWriter().println(" userTopic id :: " + userTopicKey.getId() );
					}
				}
			}
	}

}
 